import { defineStore } from 'pinia'
import { ref } from 'vue'
import router from '../router'

// 定义用户类型
export interface User {
  username: string
  password: string
  role: 'admin' | 'tourist'
  name: string
  // 可选的额外信息
  email?: string
  phone?: string
  registrationDate?: number
}

// 硬编码的用户数据
const users: User[] = [
  {
    username: 'admin',
    password: 'admin123',
    role: 'admin',
    name: '管理员',
  },
  {
    username: 'tourist',
    password: 'tourist123',
    role: 'tourist',
    name: '游客',
  },
]

export const useUserStore = defineStore(
  'beiJingUser',
  () => {
    // 当前用户信息
    const currentUser = ref<User | null>(null)
    // 登录状态
    const isLoggedIn = ref(false)

    // 登录方法
    const login = (username: string, password: string): boolean => {
      const user = users.find((u) => u.username === username && u.password === password)

      if (user) {
        currentUser.value = user
        isLoggedIn.value = true
        return true
      }
      return false
    }

    // 登出方法
    const logout = () => {
      currentUser.value = null
      isLoggedIn.value = false
      router.push('/login')
    }

    // 检查是否有权限访问
    const hasPermission = (requiredRole: 'admin' | 'tourist' | string[]): boolean => {
      if (!currentUser.value) return false

      if (Array.isArray(requiredRole)) {
        return requiredRole.includes(currentUser.value.role)
      }

      return currentUser.value.role === requiredRole
    }

    // 检查用户角色
    const isAdmin = (): boolean => {
      return currentUser.value?.role === 'admin'
    }

    const isTourist = (): boolean => {
      return currentUser.value?.role === 'tourist'
    }

    // 注册游客用户
    const registerTourist = (userData: {
      username: string
      password: string
      name: string
      email?: string
      phone?: string
    }): boolean => {
      // 检查用户名是否已存在
      const existingUser = users.find((u) => u.username === userData.username)
      if (existingUser) {
        return false
      }

      // 创建新用户
      const newUser: User = {
        username: userData.username,
        password: userData.password,
        name: userData.name || '游客',
        role: 'tourist',
        email: userData.email,
        phone: userData.phone,
        registrationDate: Date.now(),
      }

      // 添加到用户列表
      users.push(newUser)

      // 自动登录
      currentUser.value = newUser
      isLoggedIn.value = true

      return true
    }

    return {
      currentUser,
      isLoggedIn,
      login,
      logout,
      hasPermission,
      isAdmin,
      isTourist,
      registerTourist,
    }
  },
  {
    persist: true, // 持久化存储
  },
)
